package com.brspace.qualitycontrol.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.brspace.qualitycontrol.entity.*;
import com.brspace.qualitycontrol.entity.Process;
import com.brspace.qualitycontrol.entity.vo.MeetApplyVo;
import com.brspace.qualitycontrol.mapper.*;
import com.brspace.qualitycontrol.service.MeetApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brspace.qualitycontrol.utils.EmptyUtil;
import com.brspace.qualitycontrol.utils.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 会议申请 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-04-02
 */
@Service
public class MeetApplyServiceImpl extends ServiceImpl<MeetApplyMapper, MeetApply> implements MeetApplyService {

    @Resource
    private MeetApplyServiceImpl meetApplyService;
    @Resource
    private ProcessMapper processMapper;
    @Resource
    private ProcessNodeMapper nodeMapper;
    @Resource
    private MeetApplyMapper meetApplyMapper;
    @Resource
    private ProcessRouterMapper routerMapper;
    @Resource
    private HandleMapper handleMapper;

    /**
     * 会议申请
     * @author Hugo
     * @date 2021-04-08 19:00
     **/
    @Override
    public int saveInfo(MeetApply meetApply) {
        if (EmptyUtil.isEmpty(meetApply.getFenId())) {
            throw new SecurityException("请选择分管领导！");
        }
        if (baseMapper.selectOne(new QueryWrapper<MeetApply>().orderByDesc("number").last("limit 1")) != null) {
            meetApply.setNumber(baseMapper.selectOne(new QueryWrapper<MeetApply>().orderByDesc("number").last("limit 1")).getNumber() + 1);
        } else {
            String[] strNow1 = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).split("-");
            meetApply.setNumber(Long.parseLong("330122" + strNow1[0] + strNow1[1] + strNow1[2] + "001"));
        }
        meetApply.setState(0);
        int id;
        try {
            id = processMapper.selectOne(new QueryWrapper<Process>().eq("flow_name", "三重一大")).getId();
            meetApply.setNodeId(nodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("p_id", id).eq("sort_num", "1")).getId());
        } catch (Exception e) {
            e.printStackTrace();
            throw new SecurityException("当前流程存在异常，请联系管理员！");
        }
        meetApply.setId(String.valueOf(IdWorker.getId(meetApply)));
        // 根据当前节点获取目标节点
        int targetId = routerMapper.selectOne(new QueryWrapper<ProcessRouter>().eq("current_id", meetApply.getNodeId())).getTargetId();
        int i = meetApplyMapper.insert(meetApply);
        meetApply.setProgress("同意");
        if (i>0){
            examine(meetApply,meetApply.getFenId(),null);
        }
        return i;
    }

    @Override
    public IPage<MeetApply> selectPage(Page<MeetApply> pageParam, Object o) {
        return baseMapper.selectPage(pageParam, null);
    }

    /**
     * 获取饼图表格所需要的数据
     * @author Hugo
     * @date 2021-04-09 14:53
     **/
    @Override
    public MeetApplyVo getTotle() {
        Calendar cal = Calendar.getInstance();
        int today= cal.get(Calendar.YEAR);
        MeetApplyVo meetApplyVo = new MeetApplyVo();
        meetApplyVo.setDecisions(baseMapper.selectCount(new QueryWrapper<MeetApply>().eq("type", "1").gt("fill_time",  String.valueOf(today))));
        meetApplyVo.setAppointment(baseMapper.selectCount(new QueryWrapper<MeetApply>().eq("type", "2").gt("fill_time",  String.valueOf(today))));
        meetApplyVo.setProject(baseMapper.selectCount(new QueryWrapper<MeetApply>().eq("type", "3").gt("fill_time",  String.valueOf(today))));
        meetApplyVo.setMoney(baseMapper.selectCount(new QueryWrapper<MeetApply>().eq("type", "4").gt("fill_time",  String.valueOf(today))));
        meetApplyVo.setTotle(baseMapper.selectList(new QueryWrapper<MeetApply>().gt("fill_time",  String.valueOf(today))).size());
        return meetApplyVo;
    }

    /**
     * 获取折线图所需数据
     * @author Hugo
     * @date 2021-04-09 14:59
     **/
    @Override
    public List<int[]> getChart() {
        List<int[]> list= new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        int today= cal.get(Calendar.YEAR);
        for (int i = 1;i<5;i++){
            int[] sz = new int[5];
        for (int a = 4;a>=0;a--){
            String st = String.valueOf(today-a);
            String st1 = String.valueOf(today-a+1);
            sz[4-a]=(baseMapper.selectCount(new QueryWrapper<MeetApply>().eq("type", i).gt("fill_time", st).lt("fill_time", st1)));
        }
            list.add(sz);

        }
        int[] zx = new int[5];
        for (int a = 4;a>=0;a--){
            String st = String.valueOf(today-a);
            String st1 = String.valueOf(today-a+1);
            zx[4-a]=(baseMapper.selectCount(new QueryWrapper<MeetApply>().gt("fill_time", st).lt("fill_time", st1)));
        }
        list.add(zx);
        return list;
    }
    /**
     * 审批
     * userName : 下一节点办理人  uid ： 当前节点办理人
     * @Author: wangt
     * @Date: 2021-04-23 16:51:43
     */
    @Override
    public R examine(MeetApply meetApply, String userName,String uid) {
        if (meetApply.getNodeId()==0) {
            throw new SecurityException("流程已结束");
        }
        if ("驳回".equals(meetApply.getProgress())) {
            if ("undefined".equals(userName) || userName==null || "null".equals(userName)){
                Handle handleList = handleMapper.selectOne(new QueryWrapper<Handle>().eq("middleman_id", uid).eq("document_id", meetApply.getId()).eq("n_id",meetApply.getNodeId()));
                userName=handleList.getHandleId();
            }
        }
        // 根据当前节点获取当前流程下的PID以及NodeName
        ProcessNode processNode = nodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("id", meetApply.getNodeId()));
        // 获取初始节点的ID
        int findId = nodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("p_id", processNode.getPId()).eq("sort_num", 1)).getId();
        // 获取最后节点的ID
        int id = nodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("p_id", processNode.getPId()).orderByDesc("sort_num").last("limit 1")).getId();
        if (meetApply.getNodeId() == findId){
            // 获取目标节点
            handleAdd(meetApply, meetApply.getUserId(), null, processNode.getPId());
            int i = routerMapper.selectOne(new QueryWrapper<ProcessRouter>().eq("current_id", meetApply.getNodeId()).eq("requirement",meetApply.getProgress())).getTargetId();
            meetApply.setNodeId(i);
            meetApply.setState(0);
            handleAdd(meetApply, userName, meetApply.getUserId(), processNode.getPId());
            baseMapper.updateById(meetApply);
            return R.ok();
        }
        // 获取当前节点的信息
        ProcessRouter processRouters = routerMapper.selectOne(new QueryWrapper<ProcessRouter>().eq("current_id", meetApply.getNodeId()).eq("requirement", meetApply.getProgress()));
        if (meetApply.getNodeId() == processRouters.getTargetId()){
            meetApply.setState(1);
            meetApply.setNodeId(0);
            handleAdd(meetApply,userName,uid, processNode.getPId());
            baseMapper.updateById(meetApply);
        }else {
            if (processRouters.getTargetId()==id){
                System.err.println("目标节点等于最后节点");
                meetApply.setState(1);
                meetApply.setNodeId(0);
                Handle handle = new Handle();
                handle.setDocumentId(meetApply.getId())
                        .setHandleId(uid)
                        .setNId(processRouters.getTargetId())
                        .setPId(processNode.getPId());
                handleMapper.insert(handle);
                baseMapper.updateById(meetApply);
            }else {
                if ("驳回".equals(meetApply.getProgress())) {
                    System.out.println("驳回");
                    meetApply.setState(0);
                    meetApply.setNodeId(processRouters.getTargetId());
                    Handle handle = new Handle();
                    handle.setDocumentId(meetApply.getId())
                            .setHandleId(uid)
                            .setMiddlemanId(userName)
                            .setPId(processNode.getPId());
                    handleMapper.insert(handle);
                    baseMapper.updateById(meetApply);
                }else {
                    meetApply.setState(0);
                    meetApply.setNodeId(processRouters.getTargetId());
                    handleAdd(meetApply,userName,uid, processNode.getPId());
                    baseMapper.updateById(meetApply);
                }
            }

        }
        return R.ok();
    }
    /**
     * dauId:下一节点办理人  , xianID : 当前节点办理人  id : 流程ID
     * @Author: wangt
     * @Date: 2021-04-26 11:01:11
     */
    public void handleAdd(MeetApply meetApply, String daiId, String xianId, int id){
        handleMapper.delete(new QueryWrapper<Handle>().eq("document_id", meetApply.getId()).eq("middleman_id", daiId));
        handleMapper.delete(new QueryWrapper<Handle>().eq("document_id", meetApply.getId()).eq("handle_id", daiId));
        Handle handle = new Handle();
        if (daiId==null){
            handle.setMiddlemanId(meetApply.getUserId());
        }else {
            handle.setMiddlemanId(daiId);
        }
        handle.setDocumentId(meetApply.getId())
                .setHandleId(xianId)
                .setPId(id).setNId(meetApply.getNodeId());
        handleMapper.insert(handle);
    }
    /**
     * 根据当前登录用户展示代办和已办
     * @Author: wangt
     * @Date: 2021-04-23 17:46:34
     */
    @Override
    public R selectPage01(int page,int limit, String uid) {
        // 代办
        List<MeetApply> list1 = new ArrayList<>();
        List<MeetApply> meetApplyPage = baseMapper.selectList( new QueryWrapper<MeetApply>().eq("user_id", uid).or().eq("fen_id", uid).or().eq("ban_id", uid));
        for (MeetApply apply : meetApplyPage) {
            // 代办数量
            Integer integer1 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", apply.getId()).eq("middleman_id", uid));
            // 已办数量
            Integer integer2 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", apply.getId()).eq("handle_id", uid));
            // 代办
            if (integer1>integer2) {
                list1.add(apply);
            }
        }
        return R.ok().data("rows",page(list1,limit,page)).data("total", list1.size());
    }
    /**
     * 已办
     * @Author: wangt
     * @Date: 2021-04-26 17:22:47
     */
    @Override
    public R selectPage02(int page, int limit, String uid) {
        // 已办
        List<MeetApply> list2 = new ArrayList<>();
        List<MeetApply> meetApplyPage = baseMapper.selectList( new QueryWrapper<MeetApply>().eq("user_id", uid).or().eq("fen_id", uid).or().eq("ban_id", uid));
        for (MeetApply meetApply : meetApplyPage) {
            // 代办数量
            Integer integer1 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", meetApply.getId()).eq("middleman_id", uid));
            // 已办数量
            Integer integer2 = handleMapper.selectCount(new QueryWrapper<Handle>().eq("document_id", meetApply.getId()).eq("handle_id", uid));
            // 已办
            if (integer2>=integer1) {
                list2.add(meetApply);
            }
        }
        return R.ok().data("rows",page(list2,limit,page)).data("total", list2.size());
    }

    /**
     * 循环截取某页列表进行分页
     * @param dataList 分页数据
     * @param pageSize  页面大小
     * @param currentPage   当前页面
     */
    public static List<MeetApply> page(List<MeetApply> dataList, int pageSize,int currentPage) {
        List<MeetApply> currentPageList = new ArrayList<>();
        if (dataList != null && dataList.size() > 0) {
            int currIdx = (currentPage > 1 ? (currentPage - 1) * pageSize : 0);
            for (int i = 0; i < pageSize && i < dataList.size() - currIdx; i++) {
                currentPageList.add(dataList.get(currIdx + i));
            }
        }
        return currentPageList;
    }
}
